package com.wus.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wus.common.core.util.MapstructUtils;
import com.wus.common.core.util.ip.AddressUtils;
import com.wus.common.log.event.OperLogEvent;
import com.wus.system.bo.SysOperLogBo;
import com.wus.system.entity.SysOperLog;
import com.wus.system.mapper.SysOperLogMapper;
import com.wus.system.request.OperLogReq;
import com.wus.system.service.ISysOperLogService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 操作日志记录 服务实现类
 * </p>
 *
 * @author wus
 * @since 2025-01-21
 */
@RequiredArgsConstructor
@Service
public class SysOperLogServiceImpl implements ISysOperLogService {

    private final Logger logger = LoggerFactory.getLogger(SysOperLogServiceImpl.class);

    private final SysOperLogMapper baseMapper;

    /**
     * 操作日志记录
     *
     * @param event 操作日志事件
     */
    @Async("threadPoolTaskExecutor")
    @EventListener
    public void operateRecord(OperLogEvent event) {
        logger.info("操作日志新增事件异步订阅：{}", event);
        SysOperLogBo operLogBo = MapstructUtils.convert(event, SysOperLogBo.class);
        insertOperLog(operLogBo);
    }

    /**
     * 新增操作日志
     *
     * @param bo 操作日志对象
     */
    public void insertOperLog(SysOperLogBo bo) {
        SysOperLog operLog =  MapstructUtils.convert(bo, SysOperLog.class);
        // 远程查询操作地点
        operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
        operLog.setOperTime(new Date());
        baseMapper.insert(operLog);
    }

    @Override
    public void addLog(OperLogReq req) {
        SysOperLogBo bo = MapstructUtils.convert(req, SysOperLogBo.class);
        insertOperLog(bo);
    }

    @Override
    public List<SysOperLog> listLog() {
        return baseMapper.selectList(Wrappers.<SysOperLog>lambdaQuery().orderByDesc(SysOperLog::getOperId).last("limit 10"));
    }
}
